package com.suxin.nio.test;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.Set;

/**
 * @author Tang
 * @classname Server
 * @description [  ]
 * @date 2021/2/1 21:22
 */
public class Server {
    public static void main(String[] args) throws Exception{
        SelectorProvider provider = SelectorProvider.provider();
        ServerSocketChannel serverSocketChannel = provider.openServerSocketChannel();
        serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",8888));
        // 非阻塞
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("server ready ....");
        while (selector.select() > 0) {
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                // 接收请求事件
                if (selectionKey.isAcceptable()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    // 读事件
                } else if (selectionKey.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1023);
                    int len = 0;
                    while ((len = socketChannel.read(byteBuffer)) != 0 && len != -1) {
                        byteBuffer.limit(len - 1);
                        byteBuffer.position(0);
                        System.out.println( "thread id: ["+ Thread.currentThread().getName() + "] msg:" + new String(byteBuffer.array()) );
                        byteBuffer.clear();
                    }
                }else {
                    System.out.println("其他未知的事件...");
                }
                iterator.remove();
            }
        }
        serverSocketChannel.close();
    }
}